package com.bilibili.task;


import com.bilibili.dto.CartoonCollectionCountDto;
import com.bilibili.mapper.PicCartoonMapper;
import com.bilibili.mapper.PicCollectionMapper;
import com.bilibili.utils.RedisOperations;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import static com.bilibili.constant.BusinessConstant.REDIS_CARTOON_COLLECTION_COUNT_KEY;


/**
 * 在服务启动的时候如果在Redis中没有点击量数据，则将点击量数据从MySQL中同步到Redis中
 */
@Component
public class MySqlCollectionCountToRedis {
    @Autowired
    private PicCartoonMapper picCartoonMapper;

    @Autowired
    private RedisOperations redisOperations;

    @PostConstruct
    public void execute() {
        //判断redis中有收藏量数据对应的key
        boolean exists = redisOperations.exists(REDIS_CARTOON_COLLECTION_COUNT_KEY);
        //如果没有，则将MySQL中的点击量数据写入Redis中
        if (!exists) {
            System.out.println("将MySQL中的漫画收藏数据同步到Redis中start...");
            List<CartoonCollectionCountDto> countDtoList = picCartoonMapper.getCartoonCollectionRank();
            Map<String, Double> clickCountMap = new LinkedHashMap<>();
            countDtoList.forEach(countDto -> clickCountMap.put(
                    String.valueOf(countDto.getId()),
                    Double.parseDouble(String.valueOf(countDto.getCollectionCount())))
            );
            redisOperations.zadd(REDIS_CARTOON_COLLECTION_COUNT_KEY, clickCountMap);
            System.out.println("将MySQL中的漫画收藏量数据同步到Redis中end...");
        }
    }

//    @PostConstruct
//    public void execute() {
//        //判断redis中有收藏量数据对应的key
//        boolean exists = redisOperations.exists(REDIS_CARTOON_COLLECTION_COUNT_KEY);
//        //如果没有，则将MySQL中的点击量数据写入Redis中
//        if (!exists) {
//            System.out.println("将MySQL中的漫画收藏数据同步到Redis中start...");
//            List<CartoonCollectionCountDto> cartoonCollectionRank = picCartoonMapper.getCartoonCollectionRank();
//            Map<String, Double> clickCountMap = new LinkedHashMap<>();
//            cartoonCollectionRank.forEach(countDto -> clickCountMap.put(
//                    String.valueOf(countDto.getId()),
//                    Double.parseDouble(String.valueOf(countDto.getCollectionCount())))
//            );
//            redisOperations.zadd(REDIS_CARTOON_COLLECTION_COUNT_KEY, clickCountMap);
//            System.out.println("将MySQL中的漫画收藏量数据同步到Redis中end...");
//        }
//    }
}
